import com.skycode.bean.NewsBean;
import com.skycode.util.DBConnection;

import java.util.Date;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class NewsDao {
    DBConnection DBConn = new DBConnection();
    // todo 后期添加分页功能
    public List<NewsBean> getList(){
        Connection conn = DBConn.getConn();
        String sql = "select * from news";
        List<NewsBean> list = new ArrayList<NewsBean>();
        list = null;
        try{
            Statement statement = conn.createStatement();
            ResultSet rs = statement.executeQuery(sql);
            while (rs.next()){
                NewsBean newsBean = new NewsBean();
                newsBean.setNewsID(rs.getInt("NewsID"));
                newsBean.setNewsTitle(rs.getString("NewsTitle"));
                newsBean.setNewsContent(rs.getString("NewsContent"));
                newsBean.setNewsTime(Integer.parseInt(rs.getString("NewsTime")));
                newsBean.setAdminName(rs.getString("AdminName"));
                list.add(newsBean);
            }
        }catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     *
     * @param news
     * @return
     */
    public int update(NewsBean news) {
        Connection conn = DBConn.getConn();
        String sql = "update news set NewsTitle=?,NewsConten=?,NewsTime=?,NewsName=? where NewsID=?";
        try {
            PreparedStatement pmst = conn.prepareStatement(sql);
            pmst.setString(1, news.getNewsTitle());
            pmst.setString(2, news.getNewsContent());
            pmst.setString(3, (new Date()).toString());
            pmst.setString(4, news.getAdminName());
            pmst.setInt(5, news.getNewsID());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }
    public int delete(int newsID){
        Connection conn = DBConn.getConn();
        try{
            String aql = "delete from news where NesID=?";
            PreparedStatement pmst = conn.prepareStatement(sql);
            pmst.setInt(1,newsID);
            return pmst.executeUpdate(sql);
        }catch (SQLException e){
            e.printStackTrace();
        }
        return  0;
    }
}
